﻿#include "mainwidget.h"
#include "ui_mainwidget.h"
#include "friendbutton.h"

MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWidget),
    login(NULL),
    socket(NULL)
{
    ui->setupUi(this);
    m_networkManager = new QNetworkAccessManager();

    if (NULL == socket)
    {
        socket = new ChatSocket;
    }
    if (NULL == login)
    {
        //创建登录对象
        qDebug()<<"login is null";
        login = new Login(socket);
    }
    if (NULL != login)
    {
        qDebug()<<"login not null";
        login->show();  //显示登录界面
    }
    friend_add = new AddFriend();
    music_mange = new Music(this);
    ui->volume->setValue(music_mange->getVolume());
    standItemModel = new QStandardItemModel();
    standItemModel->setColumnCount(5);
    ui->music_list->setEditTriggers(QAbstractItemView::NoEditTriggers);  //设置表格属性只读，不能编辑
    ui->music_list->setModel(standItemModel);    //挂载表格模型
    ui->music_list->setMouseTracking(true);
    connect(ui->music_list, SIGNAL(entered(QModelIndex)),this, SLOT(showToolTip(QModelIndex)));
    connect(login->getServerInfo(),SIGNAL(setInfoSuccess(QString,uint)),
           socket,SLOT(slotConnectToServer(QString,uint)));
    connect(socket,SIGNAL(logonSuccess(int,QString,QString)),this,SLOT(slotLogonSuccess(int,QString,QString)));
    connect(m_networkManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(slotReplyFinished(QNetworkReply *)));
    connect(socket, SIGNAL(friendListSucc(QJsonObject)), this, SLOT(slotFriendList(QJsonObject)));
    connect(socket, SIGNAL(chatDataPrivate(QJsonObject)),this, SLOT(slotChatDateDeal(QJsonObject)));
    connect(music_mange, SIGNAL(refreshMusicList(QVector<SONG>)),this, SLOT(slotRefreshMusicList(QVector<SONG>)));
    connect(music_mange->player,&QMediaPlayer::positionChanged,this,&MainWidget::updatePosition);
    connect(music_mange->player,&QMediaPlayer::durationChanged,this,&MainWidget::updateDuration);
    connect(login,SIGNAL(testLogin(int,QString,QString)),this,SLOT(slotLogonSuccess(int,QString,QString)));
}

void MainWidget::slotLogonSuccess(int id, QString username, QString icon)
{
    this->show();
    if (NULL != login)
    {
        login->hide();
        delete login;
    }
    this->id = id;
    this->uname = username;
    ui->label_username->setText(username);
    ui->label_3->setText(QString("id:%1").arg(id));

    layout_friend = new QVBoxLayout();
    layout_group = new QVBoxLayout();
    ui->toolBox->widget(0)->setLayout(layout_friend);
    ui->toolBox->widget(1)->setLayout(layout_group);

    socket->getFriendList(id);
    QNetworkRequest request;
    request.setUrl(QUrl(icon));
    m_networkManager->get(request);

    /***demo****/
//    FriendButton *fb = new FriendButton(1001,":/resource/login.png","mason");
//    layout_friend->addWidget(fb->getButton());
}
//connect(socket, SIGNAL(chatDataPrivate(QJsonObject)), fb->getChatWidget(), SLOT(slotNewMessagePrivate(QJsonObject)));

void MainWidget::slotChatDateDeal(QJsonObject root)
{
    qDebug()<<root[STR_MESSAGE_DATA].toString();
    int send_id = root[STR_SEND_ID].toInt();
    for (int i = 0; i < friend_list.size(); i++)
    {
        if (friend_list.at(i)->getFriendId() == send_id)
        {
            if (friend_list.at(i)->getChatWidget() == NULL)
            {
                qDebug()<<"have chat widget "<<send_id;
                friend_list[i]->createChatWidget(socket,id,uname);
            }
            friend_list.at(i)->getChatWidget()->NewMessagePrivate(root);
        }
    }

}

void MainWidget::slotFriendList(QJsonObject root)
{
    int num = root[STR_NUM].toInt();
    for (int i =0; i < num; i++)
    {
        QString node = QString("%1").arg(i);
        QJsonObject temp = root[node].toObject();
        FriendButton *fb = new FriendButton(temp[STR_FRIEND_ID].toInt(),temp[STR_ICON].toString(),temp[STR_FRIEND_NAME].toString(),temp[STR_REMARK].toString());
        layout_friend->addWidget(fb->getButton());
        friend_list.append(fb);
        connect(fb->getButton(),&QToolButton::clicked,
                [=]()
                {
                    qDebug()<<"click fid "<<temp[STR_FRIEND_ID].toInt();
                    //创建聊天窗口
                    fb->createChatWidget(socket,id,uname);
                }
                );
    }
}

void MainWidget::slotRefreshMusicList(QVector<SONG> music_list)
{
    for(int i=0;i<music_list.size();i++)
    {
        qDebug()<<"add"<<i;
        QStandardItem *standItem1 = new QStandardItem(tr("%1").arg(music_list.at(i).songname));
        QStandardItem *standItem2 = new QStandardItem(tr("%1").arg(music_list.at(i).fartist));
        standItemModel->setItem(i,0,standItem1);                                //表格第i行，第0列添加一项内容
        standItemModel->setItem(i,1,standItem2);                                //表格第i行，第1列添加一项内容
        QPushButton *listen_PushButton=new QPushButton;
        QPushButton *add_PushButton=new QPushButton;
        QPushButton *dowland_Button = new QPushButton;
        listen_PushButton->setText(QStringLiteral("播放"));
        add_PushButton->setText(QStringLiteral("添加"));
        dowland_Button->setText(QStringLiteral("下载"));
        ui->music_list->setIndexWidget(standItemModel->index(i,2),listen_PushButton);    //向表格单元添加一个控件
        ui->music_list->setIndexWidget(standItemModel->index(i,3),add_PushButton);
        ui->music_list->setIndexWidget(standItemModel->index(i,4),dowland_Button);
        connect(listen_PushButton,&QPushButton::clicked,
                [=]()
                {
                    music_mange->playMusic(music_list.at(i));   //播放
                }
               );

    }

//         listen_PushButton->setText(QStringLiteral("播放"));
//         add_PushButton->setText(QStringLiteral("添加"));
//         ui->resultList->setIndexWidget(standItemModel->index(i,2),listen_PushButton);    //向表格单元添加一个控件
//         ui->resultList->setIndexWidget(standItemModel->index(i,3),add_PushButton);

//    }
}


void MainWidget::updatePosition(qint64 position)//接收歌曲位置改变，那么滑块的位置也要变
{
    ui->horizontalSlider->setValue(position);//设置滑块位置
    qint64 seconds=position/1000;
    const qint64 minutes=seconds/60;
    seconds-=minutes*60;
    ui->time->setText(QStringLiteral("%1:%2/%3").arg(minutes, 2, 10, QLatin1Char('0')).arg(seconds, 2, 10, QLatin1Char('0')).arg(timeall));

}
void MainWidget::updateDuration(qint64 duration)//更新播放歌曲的时间
{
    ui->horizontalSlider->setRange(0,duration);//根据播放时长来设置滑块的范围
    ui->horizontalSlider->setEnabled(duration>0);
    ui->horizontalSlider->setPageStep(duration/10);//以及每一步的步数
    qint64 seconds=duration/1000;
    const qint64 minutes=seconds/60;
    seconds-=minutes*60;
    timeall = QStringLiteral("%1:%2").arg(minutes, 2, 10, QLatin1Char('0')).arg(seconds, 2, 10, QLatin1Char('0'));

}

// 响应结束，进行结果处理-图片显示或错误处理
void MainWidget::slotReplyFinished(QNetworkReply *reply)
{

    // 获取响应状态码，200表示正常
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();
        QPixmap pixmap;
        pixmap.loadFromData(bytes);
        QSize picSize(64,64);
        pixmap.scaled(picSize, Qt::KeepAspectRatio);
        ui->label_icon->setPixmap(pixmap);
    }
    else
    {
        // 错误处理-显示错误信息，或显示上一次缓存的图片或叉图。
    }
}
void MainWidget::closeEvent(QCloseEvent *event)
{
    //|窗口关闭之前需要的操作~
    for (int i = 0; i < friend_list.size(); i++)
    {
        qDebug()<<"close i = "<<i;
        if (!(friend_list[i]->ChatWidgetIsNull()))
        {
            friend_list[i]->getChatWidget()->close();
        }
        delete friend_list[i];
    }
}


MainWidget::~MainWidget()
{
    delete ui;

}

void MainWidget::on_pushButton_3_clicked()
{
    music_mange->sortMusic(ui->sort_text->text());
}

void MainWidget::on_volume_valueChanged(int value)
{
    music_mange->setVolume(value);
}

void MainWidget::on_horizontalSlider_sliderMoved(int position)
{
    quint64 pos = position;
    music_mange->player->setPosition(pos);
}

void MainWidget::on_pushButton_clicked()
{
    friend_add->show();
}
